import actionInfo from '../action'
import UserModel from '../interface/userinterface';
import { userQuery, userReduce, userAdd } from "../service/userService";

interface Action {
    type: string,
    payload: any
}
interface IState {
    list: UserModel[]
}

function userReducer(state: IState = { list: [] }, action: Action) {
    switch (action.type) {
        case actionInfo.ADD:
            return { list: [...state.list, action.payload] }

        case actionInfo.REDUCE:
            return { list: state.list.filter((item) => item.id !== action.payload) }

        case actionInfo.CHANGE:
            return () => { }

        case actionInfo.QUERY:
            return { list: action.payload }
        default:
            return state
    }
}
// export const asyncAddUser = async (params) => {
//     let { data } = await userAdd(params);//做异步请求
//     addUser(data);//
// }
export const asyncAddUser = (params: UserModel) => async (dispatch: any) => {
    let { data } = await userAdd(params);//做异步请求
    dispatch(addUser(data));//
}
export const addUser = (payload: UserModel) => {
    return {
        type: actionInfo.ADD,
        payload
    }
}

// export const asyncReduceUser = async (params) => {
//     await userReduce(params);//做异步请求
//     reduceUser(params);//
// }
export const asyncReduceUser = (params: number) => async (dispatch: any) => {
    await userReduce(params);//做异步请求
    dispatch(reduceUser(params));//
}
export const reduceUser = (payload: number) => {
    return {
        type: actionInfo.REDUCE,
        payload
    }
}

export const changeUser = (payload: number) => {
    return {
        type: actionInfo.CHANGE,
        payload
    }
}

// export const asyncQueryUser = async (params) => {
//     await userQuery(params);//做异步请求
//     queryUser(params);//
// }
export const asyncQueryUser = (params: string) => async (dispatch: any) => {
    let { data } = await userQuery(params); //做异步请求
    //调用同步
    dispatch(queryUser(data)); //
};
export const queryUser = (payload: string) => {
    return {
        type: actionInfo.QUERY,
        payload
    }

}

export default userReducer;